
import pandas as pd
import numpy as np
import os
import cv2


# 获得图片路径列表，并且划分训练集和测试集
all_parent_path = []
all_data_list = []
all_label_list = []

source_path = r"E:\jupyter-notebook\TeacherWork\data\shapes"
for p in os.listdir(source_path):
    all_parent_path.append(os.path.join(source_path, p))

#获取所有的图像和对应标签的列表
for img_parent_path in all_parent_path:
    for img in os.listdir(img_parent_path):
        all_data_list.append(os.path.join(img_parent_path, img))
        all_label_list.append(img_parent_path.split("\\")[-1])


print(all_data_list[200])
print(all_label_list[200])




# img表示输入的图片，即为需要进行形状判断的图片
img = all_data_list[200]
frame = cv2.imread(img)
h, w, ch = frame.shape
result = np.zeros((h, w, ch), dtype=np.uint8)
# 二值化图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
#cv2.imshow("input image", frame)
#print(cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE))
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in range(len(contours)):
            # 提取与绘制轮廓
            cv2.drawContours(result, contours, cnt, (0, 255, 0), 2)

            # 轮廓逼近
            epsilon = 0.05 * cv2.arcLength(contours[cnt], True)
            approx = cv2.approxPolyDP(contours[cnt], epsilon, True)
            #print(approx)

            # 分析几何形状
            corners = len(approx)
            print(corners)
            shape_type = ""
            if corners == 3:
                shape_type = "三角形"
                print(shape_type)
            if corners == 4:
                shape_type = "矩形"
                print(shape_type)
            if corners > 4:
                shape_type = "圆形"
                print(shape_type)

